<template>
  <div>
    <div :style="topstyle" id="topeDiv">
      <span style="font-size:16px;margin-right:30px;display:inlne"><h4 style="display: inline;">加载本地文件:</h4></span>
      <input style="font-size:16px;" type="file" @change="uploadExcel" />
      <v-btn @click="saveSheetData" style="height:25px;margin-left:20px" class="cyan">保存</v-btn>
      <v-btn @click="downloadExcel" style="height:25px;margin-left:20px" class="cyan">导出</v-btn>
    </div>

    <div
      id="showpos"
      :style="secondstyle"
    ></div>
  </div>
</template>

<script>
// import luckysheet from 'luckysheet'
import LuckyExcel from 'luckyexcel'
//导入库export.js 这个文件是es6的，不能在普通的HTML文件直接引入js文件（虽然都是js文件，但是有区别，具体请百度es6与es5）！需要把es6转es5才可以直接引入使用！
import {exportExcel} from '../../plugins/export'
import sheetData from '../../plugins/LuckysheetInit'

export default {
  name: 'vLuckySheet',
  props: {
    msg: String
  },
  data(){
    return {
      topstyle: 'display:none',
      secondstyle: 'margin:0px;padding:0px;position:absolute;width:100%;height:870px;left: 0px;top: 0px;bottom:0px;',
      isMaskShow: false,
      dataSheets: sheetData.sheets,
      sheet_instance: null,
      filename: this.$route.params.name,
      common: this.$route.params.common,
    }
  },
  created(){
    // document.getElementById('saveSheet').addEventListener('click', this.saveSheetData)
  },
  mounted(){
    this.initLuckysheet()
  },
  beforeDestroy(){
    this.saveFile()
    window.luckysheet.destroy()
  },
  methods:{
    initLuckysheet() {
      console.log("init open luckysheet")
      let post_data = {'filename': this.filename}
      if(this.common) {
        // todo：协同编辑时应该去从redis数据库读取数据
        this.topstyle = 'position: absolute;margin-left:0px;top:0;height:0px;display:none'
        this.secondstyle = 'margin:0px;padding:0px;position:absolute;width:100%;height:870px;left: 0px;top: 0px;bottom:0px;'
        let options = {
          container: 'showpos', //luckysheet为容器id
          title: this.filename,
          lang: 'zh', // 设定表格语言
          showinfobar: false,
          myFolderUrl: '#', //作用：左上角<返回按钮的链接
          allowUpdate: true,
          allowEdit: true,
          updateUrl: "ws://" + window.location.hostname + ":" + window.location.port + "/api/job/ws/sheet/" + this.filename + "/",
          loadUrl: "/api/markdown/sheetEdit/",
          gridKey: this.filename,
        };

        console.log(options)
        this.sheet_instance = window.luckysheet.create(options);
      }else {
        this.$api.doc.getContent(post_data).then(res => {
          if (res.data.code === 200) {
            this.topstyle = 'position: absolute;margin-left:50px;top:0px;margin-top:5px;height:30px;display:block'
            this.secondstyle = 'margin:0px;padding:0px;position:absolute;width:100%;height:850px;left: 0px;top: 35px;bottom:0px;'
            let options3 = {
              container: 'showpos', //luckysheet为容器id
              title: this.filename,
              lang: 'zh', // 设定表格语言
              showinfobar: false,
              data: this.dataSheets
            };
            options3.data = res.data.data
            console.log(options3)
            this.sheet_instance = window.luckysheet.create(options3);
          }
        })
      }
    },
    uploadExcel(evt){
        const files = evt.target.files;
        if(files==null || files.length==0){
            alert("No files wait for import");
            return;
        }

        let name = files[0].name;
        let suffixArr = name.split("."), suffix = suffixArr[suffixArr.length-1];
        if(suffix!="xlsx"){
            alert("Currently only supports the import of xlsx files");
            return;
        }
        LuckyExcel.transformExcelToLucky(files[0], function(exportJson, luckysheetfile){
          console.log(exportJson)
          console.log(luckysheetfile)
          if(exportJson.sheets==null || exportJson.sheets.length==0){
              alert("Failed to read the content of the excel file, currently does not support xls files!");
              return;
          }
          window.luckysheet.destroy();
          let opt3 = {
              container: 'showpos', //luckysheet is the container id
              showinfobar:false,
              title:exportJson.info.name,
          };
          opt3.data = exportJson.sheets;
          this.sheet_instance = window.luckysheet.create(opt3);
        });
    },
    downloadExcel(){
      console.log('get sheet data')
      let sheetdatas = window.luckysheet.getluckysheetfile();
      console.log(sheetdatas)
      exportExcel(sheetdatas, this.filename)
    },
    saveFile(){
      let get_data = {'gridKey': this.filename}
      if(this.common){
        this.$api.doc.saveFile(get_data).then(res=>{
          console.log(res)
        })
      }else {
        this.saveSheetData()
      }
    },
    saveSheetData(){
      console.log('saveSheetData ...')
      let sheetdata = window.luckysheet.getluckysheetfile()
      console.log(sheetdata)
      let post_data = {'filename': this.filename, 'data': JSON.stringify(sheetdata)}
      this.$api.doc.uploadExcelData(post_data).then(res=>{
        console.log(res)
        if(res.data.code === 1){
          console.log('保存成功！')
        }
      })
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>
